package com.xindaoapp.happypet.fragment;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnLoadmoreListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnPullEventListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.HomeData;
import com.xindaoapp.happypet.bean.HomeEntity;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.SharePrefUtil;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.RollViewPager;
import com.xindaoapp.happypet.view.RoundImageView;

@SuppressLint("NewApi")
public class Club_JingFragement2 extends XDBaseFragment {
    private static Context context;
    private static Club_JingFragement2 j;
    private RelativeLayout no_data;
    private ClubBroadCast mZanHuifubroadCast;

    private boolean flag = false; // 是否复用缓存
    /** 返回顶部 */
    private View mBackToTop;

    // private RelativeLayout rl_search;
    // private TextView tv_search;

    private PullToRefreshStaggeredGridView ptrgv;
    private HomeListAdapter mAdapter = null;
    private int currentPage = 1;
    private final int totalPage = 0;

    private SharedPreferences userconfig;
    private boolean wifi;

    private RelativeLayout rl_jing;

    private GestureDetector detector;

    @Override
    public void onResume() {
        wifi = userconfig.getBoolean("wifi", true);
        super.onResume();
    }

    public static Club_JingFragement2 getInstance(Context context1) {
        j = new Club_JingFragement2();
        context = context1;
        return j;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.club_jing2, null, false);
    }

    @SuppressWarnings("static-access")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        userconfig = context.getSharedPreferences("userconfig", context.MODE_PRIVATE);
        super.onActivityCreated(savedInstanceState);
    }

    private LinearLayout mViewPager;
    private TextView tvDescription;
    private LinearLayout llPoints;

    @SuppressLint("NewApi")
    @Override
    protected void initUi() {


        no_data = (RelativeLayout) getView().findViewById(R.id.no_data);
        rl_jing = (RelativeLayout) getView().findViewById(R.id.rl_jing);
        mBackToTop = getView().findViewById(R.id.back_top);

        ptrgv = (PullToRefreshStaggeredGridView) getView().findViewById(R.id.ptrgv);
        ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrgv.getRefreshableView().setColumnCount(2);
        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View header = inflater.inflate(R.layout.xlistview_viewpage, null);
        mViewPager = (LinearLayout) header.findViewById(R.id.viewpager1);
        tvDescription = (TextView) header.findViewById(R.id.tv_image_description1);
        llPoints = (LinearLayout) header.findViewById(R.id.ll_points1);

        ptrgv.getRefreshableView().setHeaderView(header);
        View foot = inflater.inflate(R.layout.layout_loading_footer, null);
        ptrgv.getRefreshableView().setFooterView(foot);

        ptrgv.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                flag = true;
                currentPage = 1;
                getData(currentPage, 0);
            }
        });
        ptrgv.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore() {
                currentPage++;
                getData(currentPage, 1);
            }
        });
        initData();
        mBackToTop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ptrgv.getRefreshableView().setSelectionToTop();
            }
        });
        ptrgv.setOnPullEventListener(new OnPullEventListener<StaggeredGridView>() {
            @Override
            public void onPullEvent(PullToRefreshBase<StaggeredGridView> refreshView, State state,
                    Mode direction) {
                int visibility = refreshView.getChildAt(1).getVisibility();
                if (visibility == View.VISIBLE) {
                } else {
                }
            }
        });
    }

    private void initData() {
        mZanHuifubroadCast = new ClubBroadCast();
        context.registerReceiver(mZanHuifubroadCast, new IntentFilter(
                Constants.ACTION_REPLAY_SUCCESS));
        getBannerData();
    }

    private HomeEntity entity;
    private HomeBannerEntity homebanner;

    /**
     * 获取精华页轮播图数据
     * 
     * @param context
     */
    private void getBannerData() {
        if (!CommonUtil.checkNetState(context)) {
            Toast.makeText(context, R.string.pLease_check_network, 0).show();
            ptrgv.onRefreshComplete();
            imageView.setVisibility(View.GONE);
            load_fail.setVisibility(View.VISIBLE);
        }
        homebanner = (HomeBannerEntity) SharePrefUtil.getObj(context, "homebanner");
        RequestParams params = new RequestParams();
        if (homebanner == null || flag) {
            AddClient.get(Address.INDEXBANNER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    if (loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    try {
                        if (!TextUtils.isEmpty(content)) {
                            try {
                                homebanner = JSON.parseObject(content, HomeBannerEntity.class);
                                SharePrefUtil.saveObj(context, "homebanner", homebanner); // 缓存数据
                            } catch (Exception e) {
                            }
                            List<HomeBanner> list = homebanner.getArray();
                            prepareViewPage(context, list, wifi);
                            getData(currentPage, -1);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFinish() {

                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    ptrgv.setVisibility(View.VISIBLE);
                    Toast.makeText(context, R.string.get_error_data, 0).show();
                }
            });
        } else {
            if (loading.getVisibility() == View.VISIBLE) {
                animation.stop();
                loading.setVisibility(View.GONE);
            }
            // ptrgv.setVisibility(View.VISIBLE);
            List<HomeBanner> list = homebanner.getArray();
            prepareViewPage(context, list, wifi);
            getData(currentPage, -1);
        }

    }

    /**
     * 首页主题内容加载
     * 
     * @param currentPage
     * @param loadType
     * @author 贺奕凯
     */
    private void getData(final int currentPage, final int loadType) {
        if (!CommonUtil.checkNetState(context)) { // 判断是否连接网络，给用户提示
            Toast.makeText(context, R.string.pLease_check_network, 0).show();
        }
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        params.put("page", String.valueOf(currentPage));
        params.put("pagesize", "16");
        entity = (HomeEntity) SharePrefUtil.getObj(context, "jinghua");
        if (entity == null || flag) {
            AddClient.get(Address.MAINJING, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    ptrgv.onRefreshComplete();
                    if (loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    if (!TextUtils.isEmpty(content)) {
                        try {
                            entity = JSON.parseObject(content, HomeEntity.class);
                            SharePrefUtil.saveObj(context, "jinghua", entity); // 缓存主题数据
                        } catch (Exception e) {
                        }

                        if (null == entity) {
                            Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                            return;
                        }
                        List<HomeData> list = entity.getArray();

                        if (list.size() == 0) {
                            if (mAdapter.getCount() == 0) {
                                no_data.setVisibility(View.VISIBLE);
                            }
                            Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                            return;
                        }
                        if (loadType == -1) {
                            mAdapter = new HomeListAdapter();
                            ptrgv.setAdapter(mAdapter);
                            mAdapter.addItemLast(list);
                            mAdapter.notifyDataSetChanged();
                        } else if (loadType == 0) {// 说明是上拉
                            if (mAdapter.getmInfos() != null && mAdapter.getmInfos().size() != 0) {
                                mAdapter.clearItems();
                            }
                            mAdapter.addItemTop(list);
                            mAdapter.notifyDataSetChanged();
                        } else if (loadType == 1) {
                            mAdapter.addItemLast(list);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onFinish() {

                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    ptrgv.onRefreshComplete();
                    ptrgv.setVisibility(View.VISIBLE);
                    Toast.makeText(context, R.string.get_error_data, 0).show();
                }
            });
        } else {
            if (loading.getVisibility() == View.VISIBLE) {
                animation.stop();
                loading.setVisibility(View.GONE);
            }
            flag = true;

            if (null == entity) {
                Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                return;
            }

            List<HomeData> list = entity.getArray();

            if (list.size() == 0) {
                if (mAdapter.getCount() == 0) {
                    no_data.setVisibility(View.VISIBLE);
                }
                Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                return;
            }
            ptrgv.onRefreshComplete();
            if (loadType == -1) {
                mAdapter = new HomeListAdapter();
                ptrgv.setAdapter(mAdapter);
                mAdapter.addItemLast(list);
                mAdapter.notifyDataSetChanged();
            } else if (loadType == 0) {// 说明是上拉
                if (mAdapter.getmInfos() != null && mAdapter.getmInfos().size() != 0) {
                    mAdapter.clearItems();
                }
                mAdapter.addItemTop(list);
                mAdapter.notifyDataSetChanged();
            } else if (loadType == 1) {
                mAdapter.addItemLast(list);
                mAdapter.notifyDataSetChanged();
            }

            if (mAdapter.getCount() == 0) {
                Toast.makeText(context, "暂无数据", Toast.LENGTH_SHORT).show();
            } else if (currentPage == totalPage) {
            }
        }
    }

    public class HomeListAdapter extends BaseAdapter {
        private LinkedList<HomeData> mInfos;

        public HomeListAdapter() {
            context = context;
            mInfos = new LinkedList<HomeData>();
        }

        public LinkedList<HomeData> getmInfos() {
            return mInfos;
        }

        public void setmInfos(LinkedList<HomeData> mInfos) {
            this.mInfos = mInfos;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            final HomeData data = mInfos.get(position);
            if (convertView == null) {
                LayoutInflater layoutInflator = LayoutInflater.from(parent.getContext());
                convertView = layoutInflator.inflate(R.layout.activity_home_list_item, null);
                holder = new ViewHolder();
                holder.pet_icon = (RoundImageView) convertView.findViewById(R.id.pet_icon);
                holder.userIcon = (CircleImageView) convertView.findViewById(R.id.persion_icon);
                holder.title = (TextView) convertView.findViewById(R.id.tv_title);
                holder.userName = (TextView) convertView.findViewById(R.id.persion_name);
                holder.time = (TextView) convertView.findViewById(R.id.pet_time);
                holder.petName = (TextView) convertView.findViewById(R.id.pet_name);
                holder.lookTime = (TextView) convertView.findViewById(R.id.look_time);
                holder.careTime = (TextView) convertView.findViewById(R.id.care_time);
                holder.messageTime = (TextView) convertView.findViewById(R.id.message_time);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.pet_icon.mHeight = Integer.parseInt(data.getCoverheight());
            holder.pet_icon.mWidth = Integer.parseInt(data.getCoverwidth());

            // if (wifi) {
            // int available = CommonUtil.isNetworkAvailable(context);
            // if (available == 1) {
            // if (!TextUtils.isEmpty(data.getCoverpath())) {
            // Picasso.with(context).load(data.getCoverpath()).into(holder.pet_icon);
            // }
            // if (!TextUtils.isEmpty(data.getUserface())) {
            // Picasso.with(context).load(data.getUserface())
            // .placeholder(R.drawable.person_loading).into(holder.userIcon);
            // }
            // } else {
            // // holder.pet_icon.setImageResource(R.drawable.picture_loading);
            // holder.userIcon.setImageResource(R.drawable.person_loading);
            // }
            // } else {
            // if (!TextUtils.isEmpty(data.getCoverpath())) {
            // Picasso.with(context).load(data.getCoverpath()).into(holder.pet_icon);
            // }
            // if (!TextUtils.isEmpty(data.getUserface())) {
            // Picasso.with(context).load(data.getUserface())
            // .placeholder(R.drawable.person_loading).into(holder.userIcon);
            // } else {
            // Picasso.with(context).load(R.drawable.person_loading).into(holder.userIcon);
            // }
            // }
            holder.title.setText(data.getSubject());
            holder.userName.setText(data.getAuthor());

            String time = CommonUtil.formatDate();
            if (data.getAddtime().split(" ")[0].equals(time.split(" ")[0])) {// 说明是今天
                String today = data.getAddtime().split(" ")[1];
                holder.time.setText(today.substring(0, 5));
            } else {
                holder.time.setText(data.getAddtime().split(" ")[0].substring(5, 10));
            }

            holder.petName.setText(data.getForumname());
            holder.lookTime.setText(data.getViews());
            holder.careTime.setText(data.getCover() + "");
            holder.messageTime.setText(data.getReplies());

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, data.getTid());
                    intent.putExtra(Constants.KEY_FROM_PAGE, 0);
                    startActivity(intent);
                }
            });

            return convertView;
        }

        class ViewHolder {
            RoundImageView pet_icon;// 宠物头像
            CircleImageView userIcon;// 用户头像
            TextView title;// 标题
            TextView userName;// 用户名字
            TextView time;// 时间
            TextView petName;// 宠物名字
            TextView lookTime;// 查看次数
            TextView careTime;// 关注次数
            TextView messageTime;// 留言次数
        }

        @Override
        public int getCount() {
            return mInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return mInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addItemLast(List<HomeData> datas) {
            mInfos.addAll(datas);
        }

        public void clearItems() {
            if (null != mInfos) {
                mInfos.clear();
            }
        }

        public void addItemTop(List<HomeData> datas) {
            for (HomeData info : datas) {
                mInfos.addLast(info);
            }
        }
    }

    private class ClubBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getData(1, -1);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        context.unregisterReceiver(mZanHuifubroadCast);
    }

    @Override
    public boolean getUserVisibleHint() {
        return super.getUserVisibleHint();
    }

    private List<HomeBanner> list;
    private ArrayList<View> dotLists;
    private RollViewPager rollViewPager;


    public void prepareViewPage(final Context context, final List<HomeBanner> list, boolean wifi) {
        this.wifi = wifi;
        this.list = list;
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        rollViewPager =
                new RollViewPager(context, dotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {

                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    intent2.putExtra(Constants.KEY_FROM_PAGE, 0);
                                    context.startActivity(intent2);
                                }
                            }
                        });
        rollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        rollViewPager.setTitle(tvDescription, titleList);
        rollViewPager.setImageUrl(imageUrlList);
        rollViewPager.startRoll();
        mViewPager.removeAllViews();
        mViewPager.addView(rollViewPager);
    }

    class ViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        /** 判断出去的view是否等于进来的view 如果为true直接复用 */
        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        /**
         * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position
         * 
         * 修改：贺奕凯
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            // mViewPager.removeView(list.get(position %
            // imageViewList.size()).getCoverpath());
        }

        /**
         * 创建一个view
         * 
         * 修改：贺奕凯
         */
        @SuppressWarnings("deprecation")
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView iv = new ImageView(getContext());
            iv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
                    android.view.ViewGroup.LayoutParams.FILL_PARENT));
            iv.setScaleType(ScaleType.FIT_XY);
            // if (wifi) {
            // int available = CommonUtil.isNetworkAvailable(context);
            // if (available == 1) {
            // Picasso.with(getContext())
            // .load(list.get(position % list.size()).getCoverpath())
            // .placeholder(R.drawable.lunbo_loading).into(iv);
            // } else {
            // iv.setImageResource(R.drawable.lunbo_loading);
            // }
            // } else {
            // Picasso.with(getContext()).load(list.get(position % list.size()).getCoverpath())
            // .placeholder(R.drawable.lunbo_loading).into(iv);
            // }
            container.addView(iv);
            final String type = list.get(position % list.size()).getType();
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type.equals("web")) {// 跳转到详情
                        Intent intent1 = new Intent(context, HomeBannerDetailActivity.class);
                        intent1.putExtra("url", list.get(position % list.size()).getLink());
                        context.startActivity(intent1);
                    } else if (type.equals("appthread")) {// 跳转到帖子详情
                        Intent intent2 = new Intent(context, PostDetailActivity.class);
                        intent2.putExtra(Constants.KEY_POST_TID, list.get(position % list.size())
                                .getLink());
                        intent2.putExtra(Constants.KEY_FROM_PAGE, 0);
                        context.startActivity(intent2);
                    }
                }
            });

            return iv;
        }

        private Context getContext() {
            return getActivity();
        }
    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        llPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(context, 10),
                            CommonUtil.dip2px(context, 10));
            layoutParams.setMargins(5, 0, 5, 0);
            // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
            // lp.leftMargin = 10;
            View m = new View(context);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            dotLists.add(m);
            llPoints.addView(m);
        }
    }

}
